package com.order.manager.controller.Sender;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.order.manager.Model.*;
import com.order.manager.Model.other.RestBean;
import com.order.manager.service.impl.*;
import com.order.manager.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/api/sender")
public class SenderController {

    @Resource
    SenderInfoServiceImpl senderInfoService;

    @Resource
    JwtUtil jwtUtil;

    @Resource
    UserInfoServiceImpl userInfoService;

    @Resource
    OrderInfoServiceImpl orderInfoService;

    @Resource
    MenuInfoServiceImpl menuInfoService;

    @Resource
    OrderSendInfoServiceImpl orderSendInfoService;

    @Resource
    SenderExamineInfoServiceImpl senderExamineInfoService;


    @RequestMapping("/senderInfo")
    public RestBean UserInfo(HttpServletRequest request) {
        String uuid = jwtUtil.getJwtUsername(request);
        SenderInfo senderInfo = senderInfoService.getOne(new QueryWrapper<SenderInfo>().eq("user_id", uuid));
        return senderInfo != null ? RestBean.success(senderInfo) : RestBean.failure(403, "没有该信息");
    }


    @RequestMapping("/audit")
    public RestBean AuditSender(@RequestBody SenderInfo senderInfo) {
        SenderInfo sender = senderInfoService.getById(senderInfo.getSenderId());
        sender.setIsPass(senderInfo.getIsPass());
        sender.setUpdateTime(new Date());
        UserInfo userInfo = userInfoService.getById(sender.getUserId());
        if (sender.getIsPass() != 1) {
            userInfo.setRole("student");
        } else {
            userInfo.setRole("student_sender");
        }
        userInfoService.updateById(userInfo);
        return senderInfoService.updateById(sender) ? RestBean.success(sender) : RestBean.failure(500, "审核失败");
    }

    @RequestMapping("/online/count")
    public RestBean onlineCount() {
        return RestBean.success(senderInfoService.list(new QueryWrapper<SenderInfo>().eq("state", 1).eq("is_pass", 1)).size());//在线
    }

    @RequestMapping("/count")
    public RestBean count() {
        return RestBean.success(senderInfoService.list(new QueryWrapper<SenderInfo>().eq("is_pass", 1)).size());//全部
    }

    @RequestMapping("/apply")
    public RestBean applySender(@RequestBody SenderExamineInfo senderExamineInfo, HttpServletRequest request) {
        String uuid = jwtUtil.getJwtUsername(request);
        if (senderInfoService.count(new QueryWrapper<SenderInfo>().eq("user_id", uuid)) == 0) {
            String senderId = UUID.randomUUID().toString();
            SenderInfo sender = new SenderInfo();
            sender.setInputTime(new Date());
            sender.setState(1);//配送员状态删除
            sender.setIsPass(0);//审核状态
            sender.setUserId(uuid);
            sender.setSenderId(senderId);
            if (!senderInfoService.save(sender)) {
                return RestBean.failure(500, "配送员信息创建失败");
            }
            senderExamineInfo.setSenderId(senderId);
            return senderExamineInfoService.save(senderExamineInfo) ? RestBean.success(sender) : RestBean.failure(500, "申请配送员资格保存失败");
        }
        SenderInfo senderInfo = senderInfoService.getOne(new QueryWrapper<SenderInfo>().eq("user_id", uuid));
        String senderId = senderInfo.getSenderId();
        senderExamineInfo.setSenderId(senderId);
        if (senderExamineInfoService.count(new QueryWrapper<SenderExamineInfo>().eq("sender_id", senderId)) != 0) {
            return senderExamineInfoService.updateById(senderExamineInfo) ? RestBean.success(senderExamineInfo) : RestBean.failure(500, "审核提交失败");
        }
        return senderExamineInfoService.save(senderExamineInfo) ? RestBean.success(senderExamineInfo) : RestBean.failure(500, "申请配送员审核资料保存失败");
    }

    //骑手接单
    @RequestMapping("/get/order/{id}")
    public RestBean senderGetOrder(HttpServletRequest request, @PathVariable String id) {
        String uuid = jwtUtil.getJwtUsername(request);
        SenderInfo senderInfo = senderInfoService.getOne(new QueryWrapper<SenderInfo>().eq("user_id", uuid).eq("is_pass", 1));
        if (senderInfo == null) return RestBean.failure(403, "当前状态不能接单");

        String senderId = senderInfo.getSenderId();
        OrderInfo orderInfo = orderInfoService.getById(id);
        if (orderInfo.getApplyState() != 1 || orderInfo.getType() != 2 || orderSendInfoService.count(new QueryWrapper<OrderSendInfo>().eq("order_id", id)) != 0) {
            if (orderSendInfoService.getOne(new QueryWrapper<OrderSendInfo>().eq("order_id", id)).getState() != -1)
                return RestBean.failure(400, "该订单状态不能接单");
        }
        OrderSendInfo orderSendInfo = new OrderSendInfo();
        orderSendInfo.setOrderId(orderInfo.getOrderId());
        orderSendInfo.setSenderId(senderId);
        orderSendInfo.setState(0);
        return orderSendInfoService.save(orderSendInfo) ? RestBean.success(orderSendInfo) : RestBean.failure(500, "接单失败");
    }

    //骑手修改订单状态
    //-1为取消，0为正在配送，1为已送达
    @RequestMapping("/sender/state/{id}/{state}")
    public RestBean orderChargeState(@PathVariable String id, @PathVariable int state) {
        OrderInfo orderInfo = orderInfoService.getById(id);
        if (orderInfo == null) return RestBean.failure(403, "该订单信息错误");
        OrderSendInfo orderSendInfo = orderSendInfoService.getOne(new QueryWrapper<OrderSendInfo>().eq("order_id", id));
        if (orderSendInfo == null) {
            return RestBean.failure(403, "该订单没有配送员信息");
        }
        orderSendInfo.setState(state);
        if(state == -1)
            return orderSendInfoService.removeById(id)?RestBean.success():RestBean.failure(500,"订单取消失败");
        return orderSendInfoService.updateById(orderSendInfo) ? RestBean.success(orderSendInfo) : RestBean.failure(500, "订单状态修改失败");
    }

    @RequestMapping("/order/mySelf/{page}/{item}")
    public RestBean getMySenderOrder(HttpServletRequest request, @PathVariable int page, @PathVariable int item) {
        String uuid = jwtUtil.getJwtUsername(request);
        SenderInfo senderInfo = senderInfoService.getOne(new QueryWrapper<SenderInfo>().eq("user_id", uuid));
        if (senderInfo == null) return RestBean.failure(403, "当前状态不能获取订单信息");
        return RestBean.success(orderInfoService.queryByMyself(page, item, senderInfo.getSenderId()));
    }

    @RequestMapping("/query/school/{page}/{item}")
    public RestBean queryBySchool(@PathVariable int page, @PathVariable int item) {
        return RestBean.success(senderInfoService.queryBySchool(page, item));
    }

}
